<template>
  <!-- 现在 input 是作为子组件的根标签，根标签默认会把父组件的属性添加到子组件的根标签上 -->
  <input
    :class="{ success: state==='success', error: state==='fail' }"
    v-model="inputVal"
    @input="inputHandle"
    @change="checkVal"
  >
</template>

<script>
// blur      是失去焦点就会触发
// change    值被修改过并失去焦点的时候触发
export default {
  // 子组件通过 props 接收父组件传递过来的属性值
  props: ["rule", "err_message"],
  data() {
    return {
      inputVal: "",
      state: "",
    };
  },
  // 监听值的变化
  watch: {
    inputVal(val) {
      // console.log(this.rule);
      // 把字符串转换成正则对象
      // const reg = new RegExp(this.rule);
      // console.log(reg);
      // 校验当前输入框的值是否合法
      if (!this.rule.test(val)) {
        // console.log("错误");
        this.state = "fail";
      } else {
        this.state = "success";
      }
    },
  },
  methods: {
    inputHandle() {
      // console.log(this.inputVal, this.type);
      // console.log("this.$attrs.name", this.$attrs.name);
      this.$emit("aa", {
        [this.$attrs.name]: this.inputVal,
      });
    },
    checkVal() {
      if (this.state === "fail") {
        // 失败的轻提示
        this.$toast.fail(this.err_message);
      }
    },
  },
};
</script>

<style lang="less" scoped>
input {
  width: 480/540 * 100vw;
  height: 65/540 * 100vw;
  border: none;
  outline: none;
  border-bottom: 2/540 * 100vw solid #ccc;
}
.success {
  border-bottom-color: green;
}
.error {
  border-bottom-color: red;
}
</style>